
import './public-path';
import { createApp, isRef } from 'vue';
import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import './styles/element/index.scss';
import './styles/index.scss';
import './icon/iconfont.css';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';

import App from './App.vue';
import router from './router';

import i18n from './lang/index';

import loadmore from './directive/index';
import { useAuthStore } from './stores/index';

interface MicroMessage {
  path: string;
  operation?: string[];
}
declare global {
  interface Window {
    unmount: () => void;
    // 是否微前端环境
    __MICRO_APP_ENVIRONMENT__: boolean;
    // micro-app传入的基础路由
    __MICRO_APP_BASE_ROUTE__: string;
    __MICRO_APP_PUBLIC_PATH__: string;
    __MICRO_APP_NAME__: string;
    microApp: {
      addGlobalUncaughtErrorHandler: (callback: (event: Event) => void) => void;
      setGlobalData: (data: Record<string, any>) => void;
      getGlobalData: () => Record<string, any>;
      addDataListener: (callback: (data: MicroMessage) => void) => void;
      getData: () => Record<string, any>;
    };
  }
}

function dataRoute(data: MicroMessage) {
  const newPath =
    data.path.indexOf('plugin-automation') > -1 ? data.path : '/plugin-automation' + data.path;

  if (newPath) {
    router.push(newPath);
  }

  if (data.operation) {
    useAuthStore().setOperationAuth(data.operation);
  }
}

const app = createApp(App);

app.use(createPinia());
app.use(router);
app.use(i18n);
app.use(ElementPlus); // 全局使用 ElementPlus
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
const i18nMessages = (
  isRef(i18n.global.messages) ? i18n.global.messages.value : i18n.global.messages
) as any;
const i18nLocaleValue: string = isRef(i18n.global.locale)
  ? i18n.global.locale.value
  : i18n.global.locale;
app.provide('elConfig', {
  size: 'default',
  locale: i18nMessages[i18nLocaleValue],
});

app.directive('loadmore', loadmore);
app.mount('#automation-app');

// 将卸载操作放入 unmount 函数
window.unmount = () => {
  app.unmount();
};

if (window.__MICRO_APP_ENVIRONMENT__) {
  // 监听基座下发的数据变化
  const data = window.microApp.getData() as MicroMessage;
  if (data) {
    dataRoute(data);
  }
  window.microApp.addDataListener((data: MicroMessage) => {
    dataRoute(data);
  });
}
